const Sequelize = require('sequelize');
const { User, RouteList, Routers } = require('../models/user');

const Op = Sequelize.Op;

const userService = {
    async read(username, password) {
        return User.findAll({
            where: {
                username: username,
                password: password
            }
        });
    },
    // 添加token
    async modifyToken(username, token) {
        User.update(
            {
                token: token
            },
            {
                where: {
                    username: username
                }
            }
        );
    },
    // 获取用户信息
    async getUserInfo(username) {
        return User.findAll({
            attributes: ['name', 'avatar', 'roles', 'user_type'],
            where: {
                username: username
            }
        });
    },
    // 获取路由
    async getRouteList(user_type) {
        return RouteList.findAll({
            attributes: ['route'],
            where: {
                user_type: {
                    [Op.like]: `%${user_type}%`
                }
            }
        });
    },
    // 获取路由,通过父级id获取菜单
    async getRouters(p_id) {
        return Routers.findAll({
            attributes: [
                'id',
                'p_id',
                'name',
                'path',
                'icon',
                'level',
                'user_type'
            ],
            where: {
                p_id: {
                    [Op.like]: `%${p_id}%`
                }
            }
        });
    }
};

module.exports = userService;
